package com.zx.sdk.util;

import android.util.Base64;

import java.nio.charset.StandardCharsets;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AesUtil {

    private static final String AES_ECB_PKCS_5_PADDING = "AES/ECB/PKCS5Padding";

    public static String encrypt(String src, String key) throws Exception {
        if (key == null) {
            return null;
        }
        if (key.length() != 16) {
            return null;
        }
        byte[] raw = key.getBytes(StandardCharsets.UTF_8);
        SecretKeySpec keySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance(AES_ECB_PKCS_5_PADDING);
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        byte[] encrypted = cipher.doFinal(src.getBytes(StandardCharsets.UTF_8));
        return new String(Base64.encode(encrypted, Base64.DEFAULT)).replace("\n", "");//此处使用BASE64做转码功能，同时能起到2次加密的作用。
    }
}
